package com.eco.fanliapp.job.hdkitemjob;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dao.GoodsFreeMapper;
import com.eco.fanliapp.dao.SyChannelGoodsMapper;
import com.eco.fanliapp.dao.SyTljGoodsfreeMapper;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.entity.GoodsFree;
import com.eco.fanliapp.entity.SyChannelGoods;
import com.eco.fanliapp.entity.SyTljGoodsfree;
import com.eco.fanliapp.service.IAppGoodsService;
import com.eco.fanliapp.service.RedisTemplateService;
import com.eco.fanliapp.utils.ApiUtils;
import com.eco.fanliapp.utils.Convert;
import com.eco.fanliapp.utils.JsonUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取好单库失效商品
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class HDKDownGoodsTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(HDKDownGoodsTask.class);

    @Autowired
    private IAppGoodsService appGoodsService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private SyChannelGoodsMapper syChannelGoodsMapper;
    @Autowired
    private GoodsFreeMapper goodsFreeMapper;
    @Autowired
    private SyTljGoodsfreeMapper syTljGoodsfreeMapper;

    public HDKDownGoodsTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        //当前时间
        long startMillions = System.currentTimeMillis();
        log.info("***************************************开始执行好单库商品更新定时任务-DTKItemTask：executeCount=" + executeCount + "--beginTime=" + startMillions);

        int start = 0;
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.setTime(new Date());
        int end = calendar.get(java.util.Calendar.HOUR_OF_DAY);
//
//        String key = "HDK_downGoods_start_time";
//        if (redisTemplateService.hasKey(key)) {
//            start = redisTemplateService.getInt(key);
//            if (start == 23 && end != 23) {
//                start = 0;
//            }
//        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("start", start);
        data.put("end", end);
//        获取失效商品
        String str = ApiUtils.getData(ApiEnum.GET_DOWN_ITEMS, data);

        //log.info("获取的失效数据{}",str);
        JSONObject object = JSONObject.parseObject(str);
        AppGoods response = JsonUtils.getJsonToBean(object.toJSONString(), AppGoods.class);
        if (response != null && response.getCode() == 1) { //code等于1代表请求成功
            JSONArray array = JSONArray.parseArray(object.getJSONArray("data").toJSONString());
            List<AppGoods> bean = JsonUtils.getJsonToList(array.toJSONString(), AppGoods.class);
            String itemids = "";
            String tableId = "";
            for (AppGoods dataBean : bean) {
                AppGoods appGoods2 = appGoodsService.findAppGoodsByItemId(dataBean.getItemid());
                if (appGoods2 != null) {
//                    dataBean.setTableId(appGoods2.getTableId());
                    SyChannelGoods syChannelGoods = syChannelGoodsMapper.selectChannelGoodsById(Long.valueOf(appGoods2.getItemid()));
                    HashMap<String, Object> goodsFreeMap = new HashMap<>();
                    goodsFreeMap.put("goodsId", appGoods2.getItemid());
                    goodsFreeMap.put("goodsStatus", 2);
                    List<GoodsFree> goodsFree = goodsFreeMapper.selectByGoodsIds(goodsFreeMap);
                    SyTljGoodsfree syTljGoodsfree = syTljGoodsfreeMapper.selectTljGoodsfreeByItemId(Long.valueOf(appGoods2.getItemid()));
                    if (syChannelGoods == null && syTljGoodsfree == null && goodsFree.size() == 0) {
                        itemids += appGoods2.getItemid() + ",";
                        tableId += appGoods2.getTableId() + ",";
                    }
                }
            }
            int i = appGoodsService.deleteAppGoodsByIds(tableId);
            if (i > 0) {
                //删除缓存app_fixedSortGoods_list中商品的固定排序
                String fixedSort_key = "app_fixedSortGoods_list";
                if (redisTemplateService.hasKey(fixedSort_key)) {
                    String[] fixedSortItemids = Convert.toStrArray(itemids);
                    for (int y = 0; y < fixedSortItemids.length-1; y++) {
                        redisTemplateService.delMapField(fixedSort_key, fixedSortItemids[y]);
                    }
                }
//                appGoodsService.deleteIndex(itemids, "delete");
                log.info("失效商品列表   失效商品删除成功   dataBean=" + JSON.toJSONString(itemids));
            } else {
                log.info("失效商品列表   失效商品删除失败");
            }
        } else {
            log.info("失效商品列表   请求失败{}", response.getMsg());
//            redisTemplateService.del(key);
        }
//        redisTemplateService.set(key, end, 0);
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束获取好单库结束失效商品定时任务-getFullHDKItemsTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startMillions));

    }

}
